//
//  CycleCalendarSettingView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/22.
//

import SwiftUI
import UTEBluetoothRYApi
import ToastUI

struct CycleCalendarSettingView: View {
    @EnvironmentObject var appState: AppState
    @State private var showToast = false
    @StateObject var viewModel = DeviceDetailVM()
    @State private var slqts :String = "5天"
    let slqtsArray = ["2天","3天","4天","5天","6天","7天"]
    @State private var slts :String = "28天"
    let sltsArray = ["25天","26天","27天","28天","29天","30天","31天"]
    @State private var showPicker = false
    @State private var selectedDate = Date()

    var body: some View {
        VStack {
            CustomNavigationBar(rightImageName: nil, title: "生理周期设置") {}
            HStack {
                VStack(alignment: .leading, spacing: 8) {
                    Text("生理期天数")
                        .font(.system(size: 16))
                        .foregroundStyle(.white)
                    Text("您的生理期一般持续几天？")
                        .font(.system(size: 14))
                        .foregroundStyle(Color(hex: "#B1B1B1"))
                }
                .padding(.leading,16)
                Spacer()
                ZStack(alignment: .trailing) {
                    Text(slqts).font(.system(size: 16)).foregroundStyle(Color(hex: "#FFFFFF"))
                    Picker("", selection: $slqts) {
                        ForEach(slqtsArray, id: \.self) { item in
                            Text(item)
                                .foregroundColor(.white)
                        }
                    }
                    .labelsHidden()
                    .pickerStyle(.menu)
                    .frame(height: 50)
                    .environment(\.colorScheme, .dark)
                    .tint(.white)
                    .opacity(0.015)
                }
                Image("you")
                    .resizable()
                    .frame(width: 16,height: 16)
                    .padding(.trailing,16)
            }
            .frame(height: 70)
            .background(Color(hex: "#1E1E1E"))
            .cornerRadius(16)
            .padding(.horizontal,12)
            .padding(.top,12)
            
            Spacer().frame(height: 12)
            HStack {
                VStack(alignment: .leading, spacing: 8) {
                    Text("生理天数")
                        .font(.system(size: 16))
                        .foregroundStyle(.white)
                    Text("您的生理期间隔是多少天？")
                        .font(.system(size: 14))
                        .foregroundStyle(Color(hex: "#B1B1B1"))
                }
                .padding(.leading,16)
                Spacer()
                ZStack(alignment: .trailing) {
                    Text(slts).font(.system(size: 16)).foregroundStyle(Color(hex: "#FFFFFF"))
                    Picker("", selection: $slts) {
                        ForEach(sltsArray, id: \.self) { item in
                            Text(item)
                                .foregroundColor(.white)
                        }
                    }
                    .labelsHidden()
                    .pickerStyle(.menu)
                    .frame(height: 50)
                    .environment(\.colorScheme, .dark)
                    .tint(.white)
                    .opacity(0.015)
                }
                Image("you")
                    .resizable()
                    .frame(width: 16,height: 16)
                    .padding(.trailing,16)
            }
            .frame(height: 70)
            .background(Color(hex: "#1E1E1E"))
            .cornerRadius(16)
            .padding(.horizontal,12)
            .padding(.top,12)
            
            
            Spacer().frame(height: 12)
            HStack {
                VStack(alignment: .leading, spacing: 8) {
                    Text("上次生理期开始日期")
                        .font(.system(size: 16))
                        .foregroundStyle(.white)
                    Text("您上次生理期是什么时候开始的？")
                        .font(.system(size: 14))
                        .foregroundStyle(Color(hex: "#B1B1B1"))
                }
                .padding(.leading,16)
                Spacer()
                
                Text(selectedDate.toString(style: .bias))
                    .font(.system(size: 16))
                    .foregroundStyle(Color(hex: "#FFFFFF"))
                    .onTapGesture {
                        showPicker = true
                    }
                    .CustomPickerSheet(
                        isPresented: $showPicker,
                        selectedDate: $selectedDate,
                        config: CustomPickerConfig(
                            title: "生理期开始日期",
                            components: [.date]
                        )
                    )
                Image("you")
                    .resizable()
                    .frame(width: 16,height: 16)
                    .padding(.trailing,16)
                    .onTapGesture {
                        showPicker = true
                    }
                    .CustomPickerSheet(
                        isPresented: $showPicker,
                        selectedDate: $selectedDate,
                        config: CustomPickerConfig(
                            title: "生理期开始日期",
                            components: [.date]
                        )
                    )
            }
            .frame(height: 70)
            .background(Color(hex: "#1E1E1E"))
            .cornerRadius(16)
            .padding(.horizontal,12)
            .padding(.top,12)
            Spacer()
            HStack {
                Button {
                    //发送生理周期设置信息
                    viewModel.setCycleModel(cycleModel: setCycleModel()) { success
                        in
                        if success {
                            appState.navigateBack()
                        }else {
                            showToast = true
                            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                                showToast = false
                            }
                        }
                    }
                } label: {
                    Text("完成")
                        .font(.system(size: 16))
                        .foregroundStyle(Color(hex: "#242424"))
                }
            }
            .frame(maxWidth: .infinity, alignment: .center)
            .frame(height: 44)
            .gradientBackground(colors: [Color(hex: "#00F3AF"),Color(hex: "#00E9DA")], type: .linear(start: .leading, end: .trailing), cornerRadius: 22.0)
            .padding(.horizontal,12)
            .padding(.bottom,20)
            .toast(isPresented: $showToast) {
                ShowMessageView(message: "设置失败")
            }
        }
        .navigationBarHidden(true)
        .background(Color(hex: "#0A0A0A"))
        .edgesIgnoringSafeArea(.all)
    }

    func setCycleModel()->UTEModelCycleData {
        let cycleModel: UTEModelCycleData = UTEModelCycleData()
        cycleModel.historyCycleSize = getNumberParam(str: slqts)
        cycleModel.futureCycleSize = getNumberParam(str: slts)
        cycleModel.modifyTime = TimestampHelper.currentTimestamp()
        cycleModel.manualMenstrualDays = getNumberParam(str: slqts)
        cycleModel.manualCycleDays = getNumberParam(str: slts)
        let listModel : UTEModelMenstrualData = UTEModelMenstrualData()
        if let timestamp = TimestampHelper.stringToTimestamp(dateString: "\(selectedDate.toString(style: .bias)) 00:00:00") {
            print("时间: \(selectedDate.toString(style: .bias)) 00:00:00")
            print("时间戳: \(timestamp)")
            listModel.menstrualStartTime = timestamp
            listModel.menstrualEndTime = timestamp+cycleModel.manualMenstrualDays * 86400 - 86400
            listModel.easyToPregnantStartTime = listModel.menstrualEndTime + 4 * 86400 - 86400;
            listModel.easyToPregnantEndTime = listModel.easyToPregnantStartTime + 10 * 86400 - 86400
            listModel.cycleDays = getNumberParam(str: slts)
            listModel.isManual = 1
        }
        cycleModel.menstrualDataList = [listModel]
        return cycleModel
    }
    
    func getNumberParam(str:String)->Int {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        if let number = formatter.number(from: str) {
            return number.intValue
        }
        return 0
    }
    
}

#Preview {
    CycleCalendarSettingView()
}
